<template>
  <div>
    <!-- 查询表单和按钮 -->
    <div class="search-form">
      <label>开始日期:</label>
      <calendar v-model="value" show-date-only :disabled-days-of-week="disabled"
                :format="format" :clear-button="clear" :placeholder="'起始时间'"
                :lang="lang" :position="position" :on-day-click="dayClick"
                :pane="1" :range-bus="getBus" :range-status="1"/>
      <label>结束日期:</label>
      <!--      <p class="calendar-description">结束日期:</p>-->
      <calendar v-model="value2" show-date-only :disabled-days-of-week="disabled"
                :format="format" :clear-button="clear" :placeholder="'结束时间'"
                :lang="lang" :position="position" :on-day-click="dayClick"
                :pane="1" :range-bus="getBus" :range-status="2"/>
<!--      <vxe-button @click="exportData">导出</vxe-button>-->
      <button @click="exportData">导出Excel</button>
    </div>
    <vxe-table
        ref="xTable"
        resizable
        border
        v-loading="loading"
        :height="tableHeight"
        :expand-config="{iconOpen: 'vxe-icon-square-minus', iconClose: 'vxe-icon-square-plus'}"
        :data="tableData">
      <vxe-column type="seq" width="60" title="序号"></vxe-column>
      <vxe-column type="expand" title="Name" >
        <template #default="{ row }">
          <span>{{ row.name }}</span>
        </template>
        <template #content="{ row }">
          <div class="expand-wrapper">
            <vxe-table
                border
                v-loading="loading2"
                :data="rowData2Map[`${row.name}#${row.sex}`]">
              <vxe-column type="seq" width="60" title="明细序号"></vxe-column>
              <vxe-column field="name1" title="Name1"></vxe-column>
              <vxe-column field="sex1" title="Sex1"></vxe-column>
              <vxe-column field="age1" title="Age1"></vxe-column>
              <vxe-column field="t_supcon_time" title="Supcontime"></vxe-column>
            </vxe-table>
          </div>
        </template>
      </vxe-column>
      <vxe-column field="sex" title="Sex"></vxe-column>
      <vxe-column field="age" title="Age"></vxe-column>
    </vxe-table>
  </div>
</template>
<script>
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver';

import {expandRowsH, expandRowsD, expandRowsDE} from "@/exclude-folder/services/DataService3";
import Vue from "vue"; // 假设这是你的 API 服务
import Calendar from 'vue2-slot-calendar';

export default {
  name: "ExpandRows",
  mounted () {
    document.title = '展开行数据';
    this.setWindowHeight(); // 设置初始高度
    window.addEventListener('resize', this.setWindowHeight); // 监听窗口大小变化
    const currentDate = new Date().toISOString().split('T')[0];
    this.startDate = currentDate;
    this.endDate = currentDate;
  },
  data () {
    return {
      loading: true,
      loading2: true,
      tableHeight: 0, // 响应式属性，用于存储表格高度
      tableData: [], // 初始化为空数组
      rowData2Map: {}, // 用于存储每行name对应的tableData2
      startDate: '',
      endDate: '',

      // 日期空控件
      disabled: [],
      value: new Date(),
      value2: new Date(),
      format: "yyyy-MM-dd",
      clear: false,
      placeholder: "Start Date",
      position: "left",
      lang: "",
      bus: new Vue()
    }
  },
  async created() {
    try {
      this.setWindowHeight();
      window.addEventListener('resize', this.setWindowHeight);

      const currentDate = new Date().toISOString().split('T')[0];
      this.startDate = currentDate;
      this.endDate = currentDate;
      this.expandRows(this.startDate,this.endDate);

      this.loading = false;
    } catch (error) {
      this.loading = false;
      console.error('获取tableData失败:', error);
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setWindowHeight); // 组件销毁前移除监听器
  },
  components:{
    calendar: Calendar,
  },
  methods:{
    // 日期控件
    dayClick() {
      console.log('value=' + this.value);
      console.log('value2=' + this.value2);
    },
    getBus() {
      return this.bus;
    },


    handleSearch() {
      this.expandRows(this.startDate,this.endDate);

      // 如果需要，你可以在这里重置加载状态或执行其他操作
      this.loading = false;
    },

    async expandRows(startDate,endDate) {
      // 获取接口数据
      const res = await expandRowsH(startDate,endDate);
      const size = res.length;
      for (let index = 0; index < size; index++) {
        this.tableData.push({
          name: res[index].name,
          sex: res[index].sex,
          age: res[index].age,
        });
      }

      // 假设tableData已经加载完成，现在为每行数据加载tableData2
      for (let row of this.tableData) {
        this.loadTableData2(row.name,row.sex,startDate,endDate);
      }

    },
    async loadTableData2(name,sex,startDate,endDate) {
      // 假设获取tableData2的接口地址是'api/tableData2/:id'
      try {
        const res_by_names = await expandRowsD(name,sex,startDate,endDate);

        const key = `${name}#${sex}`;

        // 检查 key 是否已经在 rowData2Map 中，如果没有则初始化为空数组
        if (!this.rowData2Map[key]) {
          this.rowData2Map[key] = [];
        }

        const size = res_by_names.length;
        for (let index = 0; index < size; index++) {
          this.rowData2Map[key].push({
            name1: res_by_names[index].name1,
            sex1: res_by_names[index].sex1,
            age1: res_by_names[index].age1,
            t_supcon_time: res_by_names[index].t_supcon_time,
          });
        }
        this.loading2 = false;
      } catch (error) {
        this.loading = false;
        console.error(`获取name和sex为${name}#${sex}的tableData2失败:`, error);
      }
    },
    setWindowHeight() {
      // 计算可用高度，这里只是一个示例，你可能需要根据你的布局进行调整
      const windowHeight = window.innerHeight;
      // 假设你要留给表格之外的内容（如页眉、页脚等）100px的高度
      this.tableHeight = windowHeight - 100;
    },
    async exportData() {
      try {
        // 1. 发送请求并获取数据
        const data = await expandRowsH(this.startDate,this.endDate);
        // console.log(data)
        const workbook = XLSX.utils.book_new();


        // 转换你的数据以匹配标题
        const exportDataSheet1 = data.map(item => ({
          姓名: item.name, // 使用新的键名
          性别: item.sex, // 使用新的键名
          年龄: item.age  // 使用新的键名
        }));

        const worksheet = XLSX.utils.json_to_sheet(exportDataSheet1); // 如果你的数据是 JSON 数组


        // 或者，如果你的数据已经是二维数组：
        // const worksheet = XLSX.utils.aoa_to_sheet(data);

        // 将工作表添加到工作簿
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

        const data2 = await expandRowsDE(this.startDate,this.endDate);
        const worksheet2 = XLSX.utils.json_to_sheet(data2); // 如果你的数据是 JSON 数组
        XLSX.utils.book_append_sheet(workbook, worksheet2, 'Sheet2');// 将工作表添加到工作簿

        // 4. 生成 Excel 文件的 Blob 对象
        const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });

        // 5. 触发下载
        const blob = new Blob([wbout], { type: 'application/octet-stream' });
        saveAs(blob, 'exported-data.xlsx');

      } catch (error) {
        console.error('Error exporting data:', error);
      }
    },
  },
}
</script>
<style scoped>
.expand-wrapper {
  padding: 20px;
}
.search-form {
  margin-bottom: 10px;
}
.calendar-description {
  /* 你可以在这里添加样式来美化描述文字 */
  margin-bottom: 10px; /* 举个例子，添加一个下边距 */
}
</style>